from flask import Flask, request, jsonify, make_response
import os
import uuid

from flask_cors import CORS

app = Flask(__name__)

# 允许所有来源的跨域请求（不推荐在生产环境中使用）
CORS(app)

# 配置上传文件夹
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return make_response(jsonify({'message': 'No file part'}), 400)

    file = request.files['file']

    # 如果用户没有选择文件，浏览器会提交一个空的文件名
    if file.filename == '':
        return make_response(jsonify({'message': 'No selected file'}), 400)

    if file and allowed_file(file.filename):
        file_id = str(uuid.uuid4())  # 生成文件ID
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], file_id + '_' + file.filename)
        file.save(file_path)  # 保存文件

        return make_response(jsonify({
            'file_id': file_id,
            'message': 'File uploaded successfully',
            'status_code': 200
        }), 200)
    else:
        return make_response(jsonify({
            'message': 'Allowed file types are txt, pdf, png, jpg, jpeg, gif',
            'status_code': 400
        }), 400)


if __name__ == '__main__':
    app.run(debug=False)